package com.sys.sysserver.service.impl;

import com.sys.sysserver.domain.constant.ExceptionConstant;
import com.sys.sysserver.domain.dto.UserLoginDTO;
import com.sys.sysserver.domain.exception.PasswordNotMatchException;
import com.sys.sysserver.domain.exception.UserNotFoundException;
import com.sys.sysserver.domain.po.User;
import com.sys.sysserver.mapper.UserMapper;
import com.sys.sysserver.service.LoginService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

@Slf4j
@Service
@RequiredArgsConstructor
public class LoginServiceImpl implements LoginService {
    private final UserMapper userMapper;

    @Override
    public User login(UserLoginDTO userLoginDTO) throws Exception {
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();

        User user = userMapper.getByUsername(username);

        if (user == null) throw new UserNotFoundException(ExceptionConstant.USER_NOT_FOUND);

        password = DigestUtils.md5DigestAsHex(password.getBytes());

        log.info("\n\n数据库中的密码:{}\n\n", user.getPassword());
        log.info("\n\n前端输入的密码加密后:{}\n\n", password);

        if (!password.equals(user.getPassword()))
            throw new PasswordNotMatchException(ExceptionConstant.PASSWORD_NOT_MATCH);

        return user;
    }
}
